package com.opencee.cloud.uaa.config;

import com.opencee.cloud.core.security.SecurityProperties;
import com.opencee.cloud.core.security.SecurityUtils;
import com.opencee.cloud.uaa.constants.UaaConstants;
import com.opencee.cloud.uaa.provider.service.AppClientDetailsService;
import com.opencee.cloud.uaa.provider.service.UsernameUserDetailService;
import com.opencee.common.security.oauth2.CustomAuthorizationCodeServices;
import com.opencee.common.security.oauth2.CustomOauth2WebResponseExceptionTranslator;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.sql.DataSource;


/**
 * 平台认证服务器配置
 *
 * @author liuyadu
 */
@Configuration
@EnableAuthorizationServer
@EnableConfigurationProperties(value = {UaaProperties.class})
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private AppClientDetailsService clientDetailsService;
    @Autowired
    private UsernameUserDetailService userDetailsService;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private ApprovalStore approvalStore;
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 访问日志队列
     *
     * @return
     */
    @Bean
    public Queue queueLoginSuccess() {
        Queue queue = new Queue(UaaConstants.QUEUE_LOGIN_SUCCESS);
        return queue;
    }

    /**
     * 令牌存放
     *
     * @return
     */
    @Bean
    public TokenStore tokenStore(SecurityProperties securityProperties) throws Exception {
        tokenStore = SecurityUtils.buildJwtTokenStore(securityProperties);
        return tokenStore;
    }

    /**
     * 授权码
     *
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
        authorizationCodeServices = new CustomAuthorizationCodeServices(dataSource);
        return authorizationCodeServices;
    }

    /**
     * 授权store
     *
     * @return
     */
    @Bean
    public ApprovalStore approvalStore(DataSource dataSource) {
        approvalStore = new JdbcApprovalStore(dataSource);
        return approvalStore;
    }


    @Bean
    @Primary
    public DefaultTokenServices defaultTokenServices(SecurityProperties securityProperties) throws Exception {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(clientDetailsService);
        tokenServices.setTokenEnhancer(SecurityUtils.buildJwtTokenConverter(securityProperties));
        return tokenServices;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .authenticationManager(authenticationManager)
                .approvalStore(approvalStore)
                .userDetailsService(userDetailsService)
                .tokenServices(defaultTokenServices(securityProperties))
                .authorizationCodeServices(authorizationCodeServices);
        // 自定义确认授权页面
        endpoints.pathMapping("/oauth/confirm_access", "/oauth/confirm_access");
        // 自定义错误页
        endpoints.pathMapping("/oauth/error", "/oauth/error");
        //oauth2登录异常处理
        endpoints.exceptionTranslator(new CustomOauth2WebResponseExceptionTranslator());
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 开启/oauth/check_token
                .checkTokenAccess("permitAll()")
                // 允许表单认证
                .allowFormAuthenticationForClients();
    }

}
